package com.rbac.shiro;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.rbac.bean.Permission;
import com.rbac.bean.User;
import com.rbac.dao.PermissionDao;
import com.rbac.dao.UserDao;

public class ShiroRealm extends AuthorizingRealm {
	@Autowired
	private UserDao userDao;

	@Autowired
	private PermissionDao permissionDao;
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		User user= (User)principals.getPrimaryPrincipal();
		List<Permission> perms = permissionDao.queryPermissionsByUser(user.getId());
		
		
		Set<String> set=new HashSet<>();
		set.add("user");
		
		SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(set);
		
		for(Permission permission: perms) {
			if(StringUtils.hasText(permission.getUrl())) {
				info.addStringPermission(permission.getUrl());
			}			
		}
		
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = token.getPrincipal().toString();
		User dbUser = userDao.findByUsername(username);
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(dbUser, 
				dbUser.getPassword(), ByteSource.Util.bytes(username), super.getName());
		return simpleAuthenticationInfo;
	}
	
	public static void main(String[] args) {
		//算出盐值
		String credentials="123";
		String salt="小苏";
		String hashAlgorithmName="MD5";
		int hashIterations=1024;
		SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
		System.out.println(simpleHash);
		
	}

}
